package com.hunantv.mglive.utils;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ForegroundColorSpan;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hunantv.mglive.common.SchemaManager;
import com.hunantv.mglive.data.live.ChatData;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by qiuda on 16/5/17.
 */
public class SystemMsgNoticeUtil implements Animation.AnimationListener, View.OnClickListener {
    private final int MIN_DISPLAY_TIME = 5000;
    private final int MIN_ANIMATION_TIME = 300;
    private boolean mIsDisplay;
    private Context mContext;
    private TextView mTvNotice;
    private LinearLayout mLlViewGroup;
    private List<ChatData> mListMsg = new ArrayList<>();
    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            displayEnd();
        }
    };

    private void displayEnd() {
        mTvNotice.setText("");
        mTvNotice.clearAnimation();
        mIsDisplay = false;
        mLlViewGroup.setTag(null);
    }


    public SystemMsgNoticeUtil(Context context, TextView mTvNotice, LinearLayout mLlViewGroup) {
        this.mContext = context;
        this.mTvNotice = mTvNotice;
        this.mLlViewGroup = mLlViewGroup;
        mLlViewGroup.setOnClickListener(this);
    }


    public void startDisPlayMsg(ChatData msg) {
        synchronized (mListMsg) {
            if (mIsDisplay || !mListMsg.isEmpty()) {
                mListMsg.add(msg);
            } else {
                showMsg(msg);
            }
        }
    }


    private void showMsg(ChatData msg) {
        String content = !StringUtil.isNullorEmpty(msg.getContent()) ? msg.getContent() : "";
        content = content.replace("\n", "");
        content = content.replace("\r", "");
        int widthViewGroup = mLlViewGroup.getMeasuredWidth();
        String charSequence = setColorText(content, mTvNotice);
        int widthTextView = (int) getTextViewLength(mTvNotice, charSequence);
        LinearLayout.LayoutParams ps = (LinearLayout.LayoutParams) mTvNotice.getLayoutParams();
        if (widthTextView < widthViewGroup) {
            ps.width = LinearLayout.LayoutParams.WRAP_CONTENT;
            mTvNotice.setLayoutParams(ps);
            mTvNotice.setVisibility(View.VISIBLE);
            mHandler.sendEmptyMessageDelayed(0, MIN_DISPLAY_TIME);
        } else {
            ps.width = widthTextView;
            mTvNotice.setLayoutParams(ps);
            int distance = widthViewGroup - widthTextView;
            int duration = charSequence.length() * MIN_ANIMATION_TIME;
            TranslateAnimation translateAnimation = new TranslateAnimation(Animation.ABSOLUTE, widthViewGroup, Animation.ABSOLUTE, distance, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            translateAnimation.setInterpolator(new LinearInterpolator());
            translateAnimation.setFillAfter(true);
            translateAnimation.setDuration(duration);
            translateAnimation.setAnimationListener(this);
            mTvNotice.startAnimation(translateAnimation);
        }
        mLlViewGroup.setTag(msg.getLink());
    }

    public float getTextViewLength(TextView textView, String text) {
        TextPaint paint = textView.getPaint();
        // 得到使用该paint写上text的时候,像素为多少
        float textLength = paint.measureText(text) + 0.5f;
        return textLength;
    }

    private String setColorText(String msg, TextView textView) {
        String content = msg;
        SpannableString msgStr;
        int startIndex = content.indexOf("{#");
        int endIndex = content.indexOf("}");
        if (startIndex == -1 || endIndex == -1) {
            textView.setText(msg);
        } else {
            while (startIndex != -1 && endIndex != -1) {
                String colorStr = content.substring(startIndex + 1, endIndex);
                int nextStartIndex = content.indexOf("{#", endIndex);
                String subString;
                if (nextStartIndex != -1) {
                    subString = content.substring(endIndex + 1, nextStartIndex);
                    content = content.substring(nextStartIndex);
                } else {
                    subString = content.substring(endIndex + 1);
                    content = "";
                }
                msgStr = new SpannableString(subString);
                msgStr.setSpan(new ForegroundColorSpan(StringUtil.HextoColor(colorStr)), 0, subString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                textView.append(msgStr);

                startIndex = content.indexOf("{#");
                endIndex = content.indexOf("}");
            }
        }
        return textView.getText().toString();
    }

    @Override
    public void onAnimationStart(Animation animation) {
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        mHandler.sendEmptyMessageDelayed(0, 800);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    @Override
    public void onClick(View v) {
        Object obj = v.getTag();
        if (obj != null) {
            String tag = (String) v.getTag();
            SchemaManager.getInstance().jumpToActivity(mContext, tag, false);
        }
    }
}
